import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

import '../ex/list_ex.dart';
import '../ex/map_ex.dart';

class DioLogInterceptor extends Interceptor {
  ///请求前
  @override
  Future onRequest(
      RequestOptions options, RequestInterceptorHandler handler) async {
    String requestStr =
        "\n==================== ⭐️⭐️⭐️ 提交请求 Start ⭐️⭐️⭐️ ====================\n"
        "- Url: ${options.baseUrl + options.path}\n"
        "- Method: ${options.method}\n";

    requestStr += "- Header: ${options.headers.toJsonStr()}\n";

    final data = options.data;
    if (data != null) {
      if (data is Map) {
        requestStr += "- Body:\n${data.toJsonStr()}\n";
      } else if (data is List) {
        requestStr += "- Body:\n${data.toJsonStr()}\n";
      } else if (data is FormData) {
        final formDataMap = {}
          ..addEntries(data.fields)
          ..addEntries(data.files);
        requestStr += "- Body:\n${formDataMap.toJsonStr()}\n";
      } else {
        requestStr += "- Body:\n${data.toString()}\n";
      }
    }
    requestStr +=
        "\n==================== ⭐️⭐️⭐️ 提交请求 End ⭐️⭐️⭐️ ====================\n";
    debugPrint(requestStr);
    return handler.next(options);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    String responseStr = "";
    responseStr +=
        "\n==================== ✅✅✅ 提交完成 Start ✅✅✅ ====================\n";
    responseStr +=
        "- Url: ${response.requestOptions.baseUrl + response.requestOptions.path}\n";
    if (response.data is Map) {
      responseStr += "- Data Map: ${(response.data as Map).toJsonStr()}";
    } else if (response.data is List) {
      responseStr += "- Data List: ${(response.data as List).toJsonStr()}";
    } else if (response.data is ByteData) {
      responseStr += "- Data ByteData: ...";
    } else if (response.data is String) {
      responseStr += "- Data: ${response.data.toString()}";
    } else {
      responseStr += "- Unknow Data Type:";
    }

    responseStr +=
        "\n==================== ✅✅✅ 请求完成 End ✅✅✅ ====================\n";
    debugPrint(responseStr);
    handler.next(response);
    // super.onResponse(response, handler);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    String responseStr = "";
    responseStr +=
        "\n==================== ❌❌❌❌ 请求错误 Start ❌❌❌❌ ====================\n";
    responseStr +=
        "- Url: ${err.requestOptions.baseUrl + err.requestOptions.path}\n";

    responseStr += "- Type: ${err.type.name}\n";

    responseStr += "- Message: ${err.message}";

    responseStr +=
        "\n==================== ❌❌❌❌ 请求错误 End ❌❌❌❌ ====================\n";
    debugPrint(responseStr);
    // super.onError(err, handler);
    handler.next(err);
  }
}
